var express = require('express');
var crypto = require('crypto');
var rongSDK = require( '../rong' );
rongSDK.init('c9kqb3rdkh35j', '1bFa3S9kWnKy');
var router = express.Router();

/*
 * 获取凭证
 * 使用用户名和密码获取凭证
 * 认证同时获取推送系统的token，如果无法获取推送系统的token。登录同样失败。
 */
router.put('/token', function (req, res, next) {
	var phone = req.body.phone;
	var password = req.body.password;
	var type = req.body.type;

	// 参数错误
	if (!phone || !password || !type) {
		res.send(400);
		return;
	}


	var Account = null;
	switch(type) {
	case 'employer':
		Account = Db.Employer;
		break;
	case 'waiter':
		Account = Db.Waiter;
		password = Util.mixPassword(password, type);
		break;
	case 'customer':
		Account = Db.Customer;
		password = Util.mixPassword(password, type);
		break;
	case 'master':
		Account = Db.Master;
		password = Util.mixPassword(password, type);
		break;
	default:
		res.send(400, {

		});
		return;
	}
	console.log('phone', password);
	console.log('password', password);

	// 认证
	Account.find({
		phone : phone,
		password : password
	}, function(err, accounts) {
		if (err) {
			res.send(500, err);
			return;
		}

		if (accounts && accounts.length) { // 认证成功
			var dbAccount = accounts[0];
			// 生成Token
			var expire = new Date();
			expire.setTime(expire.getTime() + 86400000 * 7);

			var md5sum = crypto.createHash('md5');
			md5sum.update(dbAccount._id + expire.getTime());

			var token = {
				key : md5sum.digest('hex'),
				expire : expire
			};
			if (dbAccount.rongToken) { // 已有推送Token
				dbAccount.update({
					'token' : token
				}, function(err) {
					if (err) {
						res.send(500, err);
						return;
					}
					res.send({
						token : new Buffer(type + '^' + token.key).toString('base64'),
						rong : dbAccount.rongToken
					});
				});

			} else { // 获取融云推送Token
				rongSDK.user.getToken(type + '_' + dbAccount.phone, null, null, 'json', function(err, result) {
					if (err) {
						res.send(500, err);
						return;
					}

					var rongResult = JSON.parse(result);

					dbAccount.update({
						'token' : token,
						'rongToken' : rongResult.token
					}, function(err) {
						if (err) {
							res.send(500, err);
							return;
						}
						res.send({
							token : new Buffer(type + '^' + token.key).toString('base64'),
							rong : dbAccount.rongToken
						});
					});
				});
			}
		} else {
			res.send(403);
		}
	});
});
// 附着账户
router.attachAccount = function (req, res, next) {
	var token = req.query.token;
	var anonymous = {
		account : null,
		type : 'anonymous'
	}
	if (token) {
		token = new Buffer(token, 'base64').toString('ascii');
		var tokenType = token.split('^');
		console.log('token type : ', tokenType);
		if (tokenType.length != 2) {
			res.send(403);
			return;
		}

		var type = tokenType[0];
		var key = tokenType[1];

		var Account;
		switch(type) {
		case 'employer':
			Account = Db.Employer;
			break;
		case 'waiter':
			Account = Db.Waiter;
			break;
		case 'customer':
			Account = Db.Customer;
			break;
		case 'master':
			Account = Db.Master;
			break;
		default:
			req.cert = anonymous;
			next();
			return;
		}

		// 认证
		Account.findOne({
			'token.key' : key,
			'token.expire' :{
				$gte : new Date()
			}
		}, function(err, account) {
			if (err) {
				res.send(500, err);
				return;
			}

			if (account) { // 认证成功
				req.cert = {
					account : account,
					type : type
				};
				res.cookie('_username', (account.name ? account.name : account.phone));
			} else {
				req.cert = anonymous;
				res.cookie('_username', 'anonymous');
			}

			next();
		});
	} else {
		req.cert = anonymous;
		res.cookie('_username', 'anonymous');
		next();
	}
};
// 过滤账户
router.filterAccount = function(req, res, next) {
	if (req.cert) {
		next();
	} else {
		res.send(401);
	}
};

module.exports = router;
